package Thread;
/**死锁情况二：两个线程，两把锁，每个线程获取到一把锁后尝试获取对方的锁，加上sleep确保t1拿到object1,t2拿到object2*/
public class demo20 {
    public static void main(String[] args) throws InterruptedException {
        Object object1 = new Object();
        Object object2 = new Object();

        Thread t1 = new Thread(()->{
            synchronized (object1) {
                System.out.println("t1获取 object1 的锁");
                // 获取一个锁对象
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 获取第二个锁对象
                synchronized (object2) {
                    System.out.println("t1线程获取了两个锁对象");
                }
            }
        });

        Thread t2 = new Thread(()->{
            synchronized (object2) {
                System.out.println("t2获取 object2 的锁");
                // 获取一个锁对象
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // 获取第二个锁对象
                synchronized (object1) {
                    System.out.println("t2线程获取了两个锁对象");
                }
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}
